<template>
  <div>
    <md-field>
      <p style="text-align:center; margin-top:40px;">
        <span style="display:block; font-size:20px;">登&nbsp;&nbsp;录</span>
      </p>
    </md-field>
    <md-field>
      <md-input-item v-model="account" title='用户名' @blur="onBlur" is-highlight placeholder="test/123456"></md-input-item>
      <md-input-item v-model="password" type='password' title='密码' @blur="onBlur" is-highlight placeholder="密码"></md-input-item>
      <md-field-item></md-field-item>
      <md-button type="primary" @click="onSubmitLogin" :loading='loginLoading'>登&nbsp;录</md-button>
    </md-field>
  </div>
</template>

<script>
import { Dialog, Button, Field, FieldItem, InputItem } from 'mand-mobile'
import { login } from '@api/user'
import cookie from "@utils/store/cookie"
import { LOGIN_BACK_URL, setLoginBackUrl } from "@libs/login"

export default {
  name: "Login",
  components: {
    [Button.name]: Button,
    [Field.name]: Field,
    [FieldItem.name]: FieldItem,
    [InputItem.name]: InputItem
  },
  data () {
    return {
      account: '',
      password: '',
      loginLoading: false
    }
  },
  created () {
    if (this.$store.state.token) {
      this.$router.replace({
        path: '/'
      })
    }
  },
  methods: {
    onBlur() {
      window.scrollTo(0, document.documentElement.scrollTop || document.body.scrollTop)
    },
    onSubmitLogin () {
      console.log('account, password:', this.account, this.password)
      if (!this.account || this.account.length < 2) {
        Dialog.alert({
          title: '错误',
          content: '请填写登录账户'
        })
        return
      }
      if (!this.password || this.password.length < 2) {
        Dialog.alert({
          title: '错误',
          content: '请填写密码'
        })
        return
      }

      this.loginLoading = true
      login({ username: this.account, password: this.password })
        .then(res => {
          this.loginLoading = true
          console.log('login success ...')
          this.$store.commit('LOGIN', res.data.token)
          this.$store.dispatch('USERINFO')
          let backUrl = cookie.get(LOGIN_BACK_URL) || '/'
          if (backUrl.includes('/login')) {
            backUrl = '/'
          }
          setLoginBackUrl('')
          this.$router.replace({ path: backUrl })
        })
        .catch(err => {
          this.loginLoading = false
          console.log(err)
          Dialog.alert({
            title: '错误',
            content: err.message
          })
        })
    }
  }
}
</script>

<style scoped>

</style>
